<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="商户名称" prop="merchantName">
              <el-input v-model="queryParams.merchantName" placeholder="请输入商户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="信用代码" prop="creditCode">
              <el-input v-model="queryParams.creditCode" placeholder="请输入信用代码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="queryParams.contactPerson" placeholder="请输入联系人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['business:merchant:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['business:merchant:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['business:merchant:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['business:merchant:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="merchantList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商户ID，自增主键" align="center" prop="id" v-if="false" />
        <el-table-column label="商户名称" align="center" prop="merchantName" />
        <el-table-column label="信用代码" align="center" prop="creditCode" />
        <el-table-column label="商户分类" align="center" prop="merchantCategory">
          <template #default="scope">
            <dict-tag :options="shfl"
              :value="scope.row.merchantCategory ? scope.row.merchantCategory.split(',') : []" />
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center" prop="contactPerson" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status === 0">已审核</el-tag>
            <el-tag type="warning" v-if="scope.row.status === 1">待审核</el-tag>
            <el-tag type="danger" v-if="scope.row.status === 2">驳回</el-tag>
          </template>
        </el-table-column>
        <!--<el-table-column label="驳回原因" align="center" prop="reason" />-->
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['business:merchant:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['business:merchant:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="审核" placement="top" v-if="scope.row.status === 1">
              <el-button link type="warning" icon="CircleCheck" @click="handleAudit(scope.row)"
                v-hasPermi="['business:merchant:audit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改商户信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="merchantFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商户名称" prop="merchantName">
          <el-input v-model="form.merchantName" placeholder="请输入商户名称" />
        </el-form-item>
        <el-form-item label="信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" placeholder="请输入信用代码" />
        </el-form-item>
        <el-form-item label="商户分类" prop="merchantCategory">
          <el-checkbox-group v-model="form.merchantCategory">
            <el-checkbox v-for="dict in shfl" :key="dict.value" :label="dict.value">
              {{ dict.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="驳回原因" prop="reason">
          <el-input v-model="form.reason" placeholder="请输入驳回原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 审核对话框 -->
    <el-dialog title="审核商户" v-model="auditDialog.visible" width="600px" append-to-body class="audit-dialog">
      <div v-if="auditData" class="audit-content">
        <!-- 需求基本信息 -->
        <div class="audit-info-section">
          <div class="info-row">
            <span class="label">商户名称：</span>
            <span class="value">{{ auditData.merchantName }}</span>
          </div>
          <div class="info-row">
            <span class="label">信用代码：</span>
            <span class="value">{{ auditData.creditCode }}</span>
          </div>
          <div class="info-row">
            <span class="label">商户分类：</span>
            <span class="value">
              <dict-tag :options="shfl" :value="auditData.merchantCategory" />
            </span>
          </div>
          <div class="info-row">
            <span class="label">联系人：</span>
            <span class="value">{{ auditData.contactPerson }} / {{ auditData.contactPhone }}</span>
          </div>
        </div>
      </div>
      <!-- 审核表单 -->
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px" class="audit-form">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :value="0" border>
              <el-icon color="#67c23a">
                <CircleCheck />
              </el-icon>
              <span>审核通过</span>
            </el-radio>
            <el-radio :value="2" border>
              <el-icon color="#f56c6c">
                <CircleClose />
              </el-icon>
              <span>审核驳回</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="驳回原因" prop="reason" v-if="auditForm.status === 2">
          <el-input v-model="auditForm.reason" type="textarea" :rows="4" placeholder="请输入驳回原因" maxlength="200"
            show-word-limit />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialog.visible = false" size="large">
            <el-icon>
              <Close />
            </el-icon>
            <span>取 消</span>
          </el-button>
          <el-button :loading="auditLoading" type="primary" @click="submitAudit" size="large">
            <el-icon>
              <Check />
            </el-icon>
            <span>提交审核</span>
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Merchant" lang="ts">
import { listMerchant, getMerchant, delMerchant, addMerchant, updateMerchant, auditMerchant } from '@/api/business/merchant';
import { MerchantVO, MerchantQuery, MerchantForm } from '@/api/business/merchant/types';
import { AuditBo } from '@/api/business/services/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { shfl } = toRefs<any>(proxy?.useDict('shfl'));

const merchantList = ref<MerchantVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const merchantFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MerchantForm = {
  id: undefined,
  merchantName: undefined,
  creditCode: undefined,
  merchantCategory: [],
  contactPerson: undefined,
  contactPhone: undefined,
  status: undefined,
  reason: undefined
};
const data = reactive<PageData<MerchantForm, MerchantQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantName: undefined,
    creditCode: undefined,
    merchantCategory: undefined,
    contactPerson: undefined,
    contactPhone: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '商户ID，自增主键不能为空', trigger: 'blur' }],
    merchantCategory: [{ required: true, message: '商户分类不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
// 审核对话框
const auditDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 审核数据
const auditData = ref<MerchantVO | null>(null);
const auditLoading = ref(false);
const auditFormRef = ref<ElFormInstance>();
const currentAuditIds = ref<Array<string | number>>([]); // 用于存储当前需要审核的ID，可以是单个或批量

// 审核表单
const auditForm = reactive<AuditBo>({
  ids: '',
  status: 0,
  reason: ''
});

// 审核表单验证规则
const auditRules = {
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  reason: [
    {
      validator: (rule: any, value: string, callback: any) => {
        if (auditForm.status === 2 && !value) {
          callback(new Error('请输入驳回原因'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

/** 查询商户信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMerchant(queryParams.value);
  merchantList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  merchantFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MerchantVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加商户信息';
};
/** 审核按钮操作 */
const handleAudit = async (row: MerchantVO) => {
  const res = await getMerchant(row.id);
  auditData.value = res.data;
  currentAuditIds.value = [row.id]; // 单个审核

  // 重置审核表单
  auditForm.status = 0;
  auditForm.reason = ''; // 将remark改为reason
  auditFormRef.value?.clearValidate();

  auditDialog.visible = true;
};
/** 修改按钮操作 */
const handleUpdate = async (row?: MerchantVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getMerchant(_id);
  Object.assign(form.value, res.data);
  form.value.merchantCategory = form.value.merchantCategory.split(',');
  dialog.visible = true;
  dialog.title = '修改商户信息';
};

/** 提交按钮 */
const submitForm = () => {
  merchantFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.merchantCategory = form.value.merchantCategory.join(',');
      if (form.value.id) {
        await updateMerchant(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMerchant(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
/** 提交审核 */
const submitAudit = () => {
  auditFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      auditLoading.value = true;

      try {
        const auditRequest: AuditBo = {
          ids: currentAuditIds.value.join(','),
          status: auditForm.status,
          reason: auditForm.reason
        };

        await auditMerchant(auditRequest);

        const statusText = auditForm.status === 0 ? '通过' : '驳回';
        proxy?.$modal.msgSuccess(`审核${statusText}成功`);

        auditDialog.visible = false;
        await getList();
      } catch (error) {
        console.error('审核失败:', error);
      } finally {
        auditLoading.value = false;
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: MerchantVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除商户信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMerchant(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/merchant/export',
    {
      ...queryParams.value
    },
    `merchant_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
<style scoped lang="scss">
// ==================== 审核对话框样式 ====================
.audit-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    padding: 20px;
    margin: 0;

    .el-dialog__title {
      color: #fff;
      font-size: 18px;
      font-weight: 600;
    }

    .el-dialog__close {
      color: #fff;
      font-size: 20px;

      &:hover {
        color: #f0f0f0;
      }
    }
  }

  :deep(.el-dialog__body) {
    padding: 25px 30px;
    background-color: #f5f7fa;
  }
}

.audit-content {
  .audit-info-section {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

    .info-row {
      display: flex;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #f0f2f5;

      &:last-child {
        border-bottom: none;
      }

      .label {
        font-weight: 600;
        color: #606266;
        min-width: 100px;
        flex-shrink: 0;
      }

      .value {
        color: #303133;
        flex: 1;
      }
    }
  }

  .audit-form {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

    :deep(.el-radio-group) {
      display: flex;
      gap: 15px;

      .el-radio.is-bordered {
        padding: 12px 20px;
        border-radius: 8px;
        margin-right: 0;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        &.is-checked {
          border-width: 2px;
        }

        .el-radio__label {
          display: flex;
          align-items: center;
          gap: 6px;
          font-weight: 500;
        }
      }
    }

    :deep(.el-textarea) {
      .el-textarea__inner {
        border-radius: 8px;
        resize: none;
      }
    }
  }
}
</style>
